package com.taobao.shopcart.service.impl;


import com.taobao.base.model.RestResponse;
import com.taobao.shopcart.feignclient.HomeServiceClient;
import com.taobao.shopcart.mapper.OrderProcessMapper;
import com.taobao.shopcart.mapper.OrdersMapper;
import com.taobao.shopcart.model.dto.OrderDto;
import com.taobao.shopcart.model.po.OrderProcess;
import com.taobao.shopcart.model.po.Orders;
import com.taobao.shopcart.service.ShopCartService;
import com.taobao.utile.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

@Service
public class ShopCartServiceImpl implements ShopCartService {

    @Autowired
    private HomeServiceClient homeServiceClient;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderProcessMapper orderProcessMapper;

    SnowflakeIdGenerator snowflakeIdGenerator = new SnowflakeIdGenerator(1, 1);


    @Override
    @Transactional
    public RestResponse<Long> submitOrder(OrderDto orderDto, int userId) {

        // 1.远程调用home 减库存
        Map<Integer, Integer> goodsMap = orderDto.getQuantityMap();
        RestResponse<String> response = null;
        String goodsIds = "";
        for (Integer key : goodsMap.keySet()) {
            List<Integer> list = new ArrayList<>();
            list.add(key);
            goodsIds += key + ",";
            list.add(goodsMap.get(key));
            response = homeServiceClient.getGoodsCount(list);
            int code = response.getCode();
            if (code == -1) {
                return RestResponse.validfail(response.getMsg());
            }
        }

        // 2.订单入库
        Orders orders = new Orders();
//        long nextId = snowflakeIdGenerator.nextId();
        orders.setOrderId(ThreadLocalRandom.current().nextLong(10_000_000L, 100_000_000L));
        orders.setUserId(userId);
        orders.setGoodsIdList(goodsIds);
        orders.setStatus(orderDto.getStatus());
        orders.setTotalAmount(orderDto.getTotalPrice());
        orders.setCreatedAt(LocalDateTime.now());
        if (orderDto.getStatus() == 1) {
            orders.setPaidAt(LocalDateTime.now());
        }if (orderDto.getStatus() == 0) {
            // 未支付 添加到待处理任务
            this.addProcess(orders);
        }
        orders.setReceiverName(orderDto.getName());
        orders.setReceiverPhone(orderDto.getPhone());
        orders.setReceiverAddress(orderDto.getAddress());
        orders.setPaymentMethod("微信");
        orders.setNote("无");

        int insert = this.ordersMapper.insert(orders);
        if (insert != 1) {
            return RestResponse.validfail("订单创建失败");
        }


        return RestResponse.success( orders.getOrderId(),response.getMsg());
    }

    @Override
    public RestResponse<List<Orders>> queryOrder(int userId) {

        List<Orders> orders = ordersMapper.queryOrder(userId);

        return RestResponse.success(orders);
    }

    /**
     * 添加任务
     */
    public void addProcess(Orders order) {
        OrderProcess orderProcess = new OrderProcess();
        orderProcess.setTypes(1); // 1 支付类型
        orderProcess.setStatus(1); // 1 待处理
        orderProcess.setUpdateTime(LocalDateTime.now());
        orderProcess.setFailCount(0);
        orderProcess.setOrderId(order.getOrderId());
        if (orderProcessMapper.selectByOrderId(order.getOrderId()) == null) {
            orderProcessMapper.insert(orderProcess);
        }
    }
}
